<?php
namespace Admin\Controller;
use Admin\Model\configModel;

use Admin\Model\smsModel;
use Admin\Api\SmsApi;
use Admin\Model\settelModel;
use Admin\Model\extendModel;
use Admin\Model\UserModel;
class MerchantController extends BaseController{
	
	private $size = 6;
	
	public function __construct() {
		parent::__construct();
	}
	
	public function mainAction() {
		$callback  = urlencode(C('DOMAIN').U('Sign/in')); //回调地址
		$state  ='main'; 
	    $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->_APPID.'&redirect_uri='.$callback.'&response_type=code&scope=snsapi_base&state='.$state.'#wechat_redirect';  
	    header("Location:".$url);  
	}
	
	/**
	 * 用户登陆页面
	 */
	public function loginViewAction() {
		$this->display('Balance/register');
	}
	
	/**
	 * 用户登陆提交
	 */
	public function loginSubAction(){
		$userModel = new UserModel();
		$tel =I('tel');
		$verification=I('verification');//验证码
		if( empty($tel) || empty($verification)){
			$this->error('手机、验证码都不能为空');
		}
		if (!$this->isMobile($tel)) {
			$this->error('手机号不正确');
		}
		//短信有效时间
		$smsValid=$this->smsValidTime($tel, $verification);
		if ($smsValid['state'] == -1) {
			$this->error($smsValid['msg']);
		}
		
    	$where['tel']=$tel;
    	$where['userauth']=array('in','3,6,7,8');
    	$userItem = $userModel->getUserItem($where);
    	if (!empty($userItem)) {
    		//绑定微信号
    		$callback  = urlencode(C('DOMAIN').U('sign/in',array('userid'=>$userItem['userid']))); //回调地址
			$state  ='bind'; 
		    $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->_APPID.'&redirect_uri='.$callback.'&response_type=code&scope=snsapi_base&state='.$state.'#wechat_redirect';  
		    header("Location:".$url);  
    	}else {
    		$this->error('用户未注册');
    	}
    	
	}
	/**
	 * 结算页面
	 */
	public function accountAction() {
		$userModel = new UserModel();
		$extendModel = new extendModel();
		$settelModel = new settelModel();
		//账户余额
		$dataUser['userid']=$this->_userId;
		$bossItem = $userModel->getUserItem($dataUser);
		$balance=$bossItem['balance'];
		$openid = $bossItem['openid'];
		//佣金余额
		$dataExtend['uid'] = $this->_userId;
		$extendItem=$extendModel->getExtendInfo($dataExtend);
		$brokerage=empty($extendItem['brokerage'])?'0.00':$extendItem['brokerage'];

		$dataSettel['uid']=$this->_userId;
		$page = '1,'.$this->size;
		$settelList = $settelModel->getSettelList($dataSettel,$page);
		$dataSettle['status'] = 1;
		$settelTotal = $settelModel->getSettelTotal($dataSettel);
		
		$this->assign('settelTotal',$settelTotal);
		$this->assign('settelList',$settelList);
		$this->assign('openid',$openid);
    	$this->assign('balance',$balance);
    	$this->assign('brokerage',$brokerage);
		$this->display('Balance/balance');
    }
    
    public function historyAction() {
    	$pagenum = I('pagenum');
		$settleModel = new settelModel();
		$dataSettle['uid']=$this->_userId;
		$page = $pagenum.','.$this->size;
		$settleList = $settleModel->getSettelList($dataSettle,$page);
		if (!empty($settleList)) {
    		$this->ajaxReturn(array('state' => 1,'data'=>$settleList));
		}else{
			$this->ajaxReturn(array('state' => -1,'msg'=>'没有值'));
		}
    }
    
    private function secretkeyAction($package) {
    	$ApikeySettle = C('ApikeySettle');
    	ksort($package, SORT_STRING);
        $string1 = '';
        foreach($package as $key => $v) {
            if (empty($v)) {
                continue;
            }
            $string1 .= "{$key}={$v}&";
        }
        $string1 .= "key={$ApikeySettle}";
        $package['sign'] = strtoupper(md5($string1));
        return $package;
    }
    
    
    public function settleAction() {
    	$openid =I('openid');//结算用户openid
    	$name = I('name');//结算用户真实姓名
    	$amount = I('amount');//结算金额
    	
    	if (doubleval($amount) > 20000) {
    		$amount = 20000;
    	}
    	$amount = doubleval($amount)* 100;//单位  分
   		 if (doubleval($amount) < 1) {
    		$msg['msg'] = '提现不能少于1元';
			$url = C('DOMAIN').U('Merchant/settleFail',$msg); 
			header("Location:".$url); 
    	}
    	
    	$package['mch_appid'] = C('APPID');
    	$package['mchid'] = C('MCHID');
    	$package['check_name'] = 'FORCE_CHECK';
    	$package['nonce_str'] = $this->getRandChar(15);
    	$package['partner_trade_no'] = C('MCHID').date("YmdHis").uniqid(rand(10,99), TRUE);
    	$package['openid'] = $openid;
    	$package['re_user_name'] = $name;
    	$package['amount'] = $amount;
    	$package['desc'] = '易卡系统商户结算';
    	$package['spbill_create_ip'] = get_client_ip();
    	$package = $this->secretkeyAction($package);
        $dat = array2xml($package);
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
        $responseXml = $this->curl_post_ssl($url, $dat);
		$responseObj = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
		
		$responseArr = (array) $responseObj;
		
		//返回出错
		if ($responseArr['return_code'] == 'FAIL' ) {
			$msg['msg'] = '当前结算用户较多，系统正在处理中。烦请主人稍后再进行结算';
			$url = C('DOMAIN').U('Merchant/settleFail',$msg); 
			header("Location:".$url); 
		}
		//企业支付出错
		if ($responseArr['result_code'] == 'FAIL' ) {
			if ($responseArr['err_code'] == 'NAME_MISMATCH') {
	    		$msg['msg'] = '很抱歉！由于您输入的真实姓名与本微信号认证者的真实姓名不一致，或您所登陆的微信号还未实名认证，微信支付无法为您结算';
				$url = C('DOMAIN').U('Merchant/settleFail',$msg); 
				header("Location:".$url); 
			}elseif ($responseArr['err_code'] == 'NOTENOUGH') {
				//给张理亚发短信
				$configModel = new configModel();
				$dataConfig['id']=5;
				$configTel = $configModel->getConfigItem($dataConfig);
				$tel=trim($configTel['extra']);
				//推送间隔时间
				$dataConfig['id']=6;
				$configTime = $configModel->getConfigItem($dataConfig);
				$times = intval($configTime['extra']);
				
				$smsModel = new smsModel();
				$telData['tel']=$tel;
				$between =(time()-$time).",". time();
				$telData['createunixtime'] =array('between',$between);
	    		$isExistSmsData = $smsModel->getSmsItem($telData);
	    		if (empty($isExistSmsData)) {
	    			$content='【易卡网络】用户结算时，余额不足。请及时充值！！！';
					$smsSend = new SmsApi();
					$result = $smsSend->sendSMS($tel, $content,'true');
					$result = $smsSend->execResult($result);
					if($result[1]==0 && !empty($result)){
						$dataSms['tel']=$tel;
						$dataSms['type']=3;
						$dataSms['verification']='not_sufficient_funds';
						$dataSms['content']=$content;
						$dataSms['resptime']=$result[0];
						$dataSms['respstatus']=$result[1];
						$dataSms['msgid']=$result[2];
						$dataSms['createunixtime']=time();
						$dataSms['createtime']=date("Y-m-d H:i:s", time());
						$smsItem = $smsModel->addSms($dataSms);//单条加载
					}
	    		}
				$msg['msg'] = '当前结算用户较多，系统正在处理中。烦请主人稍后再进行结算';
				$url = C('DOMAIN').U('Merchant/settleFail',$msg); 
				header("Location:".$url); 
			}elseif ($responseArr['err_code'] == 'SENDNUM_LIMIT') {
				$msg['msg'] = '您今天结算超过限制啦。明天再结吧！！！';
				$url = C('DOMAIN').U('Merchant/settleFail',$msg); 
				header("Location:".$url); 
			}else {
				$msg['msg'] = '当前结算用户较多，系统正在处理中。烦请主人稍后再进行结算';
				$url = C('DOMAIN').U('Merchant/settleFail',$msg); 
				header("Location:".$url); 
			}
		}
		
		if ($responseArr['result_code'] == 'SUCCESS' ) {
			$settelModel = new settelModel();
			$userModel = new UserModel();
			$extendModel = new extendModel();
			
			//会员余额清零
			$whereUser['userid']=$this->_userId;
			$dataUser['balance'] = 0;
			$result = $userModel->UpUser($whereUser, $dataUser);
			
			//佣金余额清零
			$whereExtend['uid'] = $this->_userId;
			$dataExtend['brokerage'] = 0;
			$extendItem=$extendModel->upExtend($whereExtend, $dataExtend);
			
			$dataSettel = $package;
			$dataSettel['result_code'] = strval($responseArr['result_code']) ;
			$dataSettel['payment_no'] =  strval($responseArr['payment_no']);
			$dataSettel['payment_time'] = strval($responseArr['payment_time']);
			$dataSettel['uid'] = $this->_userId;
			$settelid = $settelModel->addSettel($dataSettel);
			
    		$msg['msg'] = $amount/100;
			$url = C('DOMAIN').U('Merchant/settleSuccess',$msg); 
			header("Location:".$url); 
		}
    }
	
    public function settleFailAction() {
    	$msg = I('msg');
    	$this->assign('msg',$msg);
		$this->display('Balance/balanceFail');
    }
    
    public function settleSuccessAction() {
    	$msg = I('msg');
    	$this->assign('msg',$msg);
		$this->display('Balance/balanceOk');
    }
	

	function curl_post_ssl($url, $vars, $second=30,$aHeader=array())
	{
		$ch = curl_init();
		//超时时间
		curl_setopt($ch,CURLOPT_TIMEOUT,$second);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
		//这里设置代理，如果有的话
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);	
		
		//cert 与 key 分别属于两个.pem文件
		curl_setopt($ch,CURLOPT_SSLCERT,PUBLIC_PATH.'uploads/cert/apiclient_cert.pem');
 		curl_setopt($ch,CURLOPT_SSLKEY,PUBLIC_PATH.'uploads/cert/apiclient_key.pem');
 		curl_setopt($ch,CURLOPT_CAINFO,PUBLIC_PATH.'uploads/cert/rootca.pem');
	 
		if( count($aHeader) >= 1 ){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
		}
	 
		curl_setopt($ch,CURLOPT_POST, 1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
		$data = curl_exec($ch);
		if($data){
			curl_close($ch);
			return $data;
		}
		else { 
			$error = curl_errno($ch);
			curl_close($ch);
			return false;
		}
	}
    
	
}